package com.tanhua.recommend.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.mongo.VideoScore;
import org.bson.types.ObjectId;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class VideoListener {

    @Autowired
    private MongoTemplate mongoTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(
                    name = "tanhua_video_recommend",
                    durable = "true"
            ),
            exchange = @Exchange(
                    name = "tanhua.log.exchange",
                    type = ExchangeTypes.TOPIC
            ),
            key = "log.video"
    ))
    public void videoMessage(String message) {
        //1 解析消息数据
        JSONObject jsonObject = JSON.parseObject(message);

        //查询小视频数据
        String videoId = jsonObject.getString("busId");
        Video video = mongoTemplate.findById(new ObjectId(videoId), Video.class);

        //用户id
        Long userId = jsonObject.getLong("userId");

        //操作类型
        String type = jsonObject.getString("type");

        if (video != null) {
            //2 封装评分的数据对象
            VideoScore score = new VideoScore();
            score.setUserId(userId);
            score.setVideoId(video.getVid());
            score.setDate(System.currentTimeMillis());
            score.setScore(score(type));

            //3 保存数据到MongoDB
            mongoTemplate.save(score);
        }
    }

    //计算评分
    private Double score(String type) {
        //0301为发小视频，       +2
        //0302为小视频点赞，     +5
        //0303为小视频取消点赞， -5
        //0304为小视频评论      +10
        Double score = 0d;
        switch (type) {
            case ("0301"):
                score = 2d;
                break;
            case ("0302"):
                score = 5d;
                break;
            case ("0303"):
                score = -5d;
                break;
            case ("0304"):
                score = 10d;
                break;
        }

        return score;
    }
}
